var registerNS = function(nsName) {
	var rootObject = window;
	var namespaceParts = nsName.split('.');
	for (var i = 0;i < namespaceParts.length; i++) {
		var currentPart = namespaceParts[i];
		if (!rootObject[currentPart]) {
			rootObject[currentPart] = new Object();
		}
		rootObject = rootObject[currentPart];
	}
};
registerNS("app.cache");
registerNS("app.data");
registerNS("app.dict");

if(bootbox != undefined) bootbox.setDefaults({locale: 'zh_CN'});

/*权限判断*/
app.hasAuth = function() {
	if(app.allAuthority.length > 0 && arguments.length > 0) {
		for(var i = 0 ; i < app.allAuthority.length ;i++) {
			for(var j = 0 ; j < arguments.length ;j++) {
				if(app.allAuthority[i] == arguments[j]) {
					return true;
				}
			}
		}
	}
	return false;
};

$.ajaxSetup({
	cache: false,
	headers: {
        "X-Requested-With":"XMLHttpRequest"
    },
    complete: function(XMLHttpRequest, textStatus) {
    	try {
    		var json = $.parseJSON(XMLHttpRequest.responseText);
    		var items = json.items;
    		if(!json.success && items && items.length > 0) {
    			var tmp = items[0];
    			if(tmp.msg == 'to_ajax_login') {
    				app.popupDialog({
    					url: base + '/security/ajaxLoginPage',
    					title: '登录中心',
    					id: 'ajax_login_dlg',
    					width: '530px',
    					height: '480px',
    					buttons: {
							 a: {
								label: "取消",
								className: "btn-default"
							 },
    						 b: {
    							label: "确定",
    						    className: "btn-primary",
    						    callback: function() {
    						    	var form = $("#ajax_login_dlg form");
    						    	
    						    	var pass = form.find("input[name=j_password]");
    						    	pass.val(CryptoJS.MD5(pass.val()));
    						    	app.ajaxJson(base + '/j_spring_security_check', form.serialize(), function(dd) {
						    			if(dd.success) {
						    				$("#ajax_login_dlg").modal('hide');
						    			} else if(dd.items && dd.items.length > 0) {
						    				var tmpItem = dd.items[0];
						    				var msg = '服务器错误，请重试!';
						    				if(tmpItem.msg == 'captcha_code_error') {
						    					msg = '验证码错误, 请重试!';
						    				} else if(tmpItem.msg == 'ajax_login_error') {
						    					msg = '用户名或密码错误, 请重试!';
						    				}
						    				app.showErrors('#loginErrorMsg', msg);
						    			}
						    			pass.val('');
						    		}, function(XMLHttpRequest, textStatus, errorThrown) {
						    			var tjson = $.parseJSON(XMLHttpRequest.responseText);
						    			pass.val('');
						    			if(!tjson.success && tjson.items && tjson.items.length > 0 && tjson.items[0].msg == 'ajax_denied') {
						    				$("#ajax_login_dlg").modal('hide');
						    			}
						    		});
    						    	
    						    	return false;
    						    }
    						}
    					}
    				});
    			} else if(tmp.msg == 'ajax_denied') {
    				console.log('您没有权限进行此操作!');
    			}
    		}
    	} catch(err) {
    		
    	}
    }
});

app.changePassword = function() {
	app.popupDialog({
		url: base + '/account/changePassword',
		title: '修改密码',
		id: 'ajax_change_password_dlg',
		width: '450px',
		height: '350px',
		buttons: [
			 {
				label: "取消"
			 },
			 {
				label: "确定",
			    className: "btn-primary",
			    callback: function() {
			    	var form = $("#ajax_change_password_dlg form");
			    	
			    	var pass = form.find("input[name=password]").val();
			    	var passNew = form.find("input[name=passwordNew]").val();
			    	var passNewCon = form.find("input[name=passwordNewConfirm]").val();
			    	if(!pass) {
			    		app.showErrors('#changePasswordError', '原密码不能为空!');
			    		return false;
			    	}
			    	if(!passNew) {
			    		app.showErrors('#changePasswordError', '新密码不能为空!');
			    		return false;
			    	}
			    	if(passNew != passNewCon) {
			    		app.showErrors('#changePasswordError', '两次密码输入不一致!');
			    		return false;
			    	}
			    	app.ajaxJson(base + '/account/updatePassword', form.serialize(), function(dd) {
		    			if(dd.success) {
		    				$("#ajax_change_password_dlg").modal('hide');
		    			} else if(dd.items && dd.items.length > 0){
		    				var msg = dd.items[0].msg;
		    				if(msg == 'not_login') {
		    					reminder.find('span').text('请先登录!');
		    					app.showErrors('#changePasswordError', '请先登录!');
		    				} else if(msg == 'password_new_blank') {
		    					app.showErrors('#changePasswordError', '新密码为空!');
		    				} else if(msg == 'password_error') {
		    					app.showErrors('#changePasswordError', '原密码错误!');
		    				}
		    			}
		    		});
			    	
			    	return false;
			    }
			}
		]
	});
};

app.ajaxRequest = function (url, dataType, data, callback, erroCallback) {
	data = data || {};
	dataType = dataType || 'text';
	callback = callback || function(){};
	erroCallback = erroCallback || function(){};
	$.ajax({
		 url : url,
		 dataType: dataType,
		 data: data,
		 type: 'post',
		 success: function(dd) {
			 callback(dd);
		 },
		 error:  function(dd) {
			 erroCallback(dd);
		 }
 	});
};

app.ajaxJson = function (url, data, callback, erroCallback) {
	app.ajaxRequest(url, 'json', data, callback, erroCallback);
};

app.ajaxText = function (url, data, callback, erroCallback) {
	app.ajaxRequest(url, 'text', data, callback, erroCallback);
};

app.ajaxHtml= function (url, data, callback, erroCallback) {
	app.ajaxRequest(url, 'html', data, callback, erroCallback);
};

app.sendRequest = function (url, options, callback) {
	if(!url) {
		app.alert('调用sendRequest时, url 为空');
		return;
	}
	var confirm = options.confirm || false;
	var confirmMsg = options.confirmMsg || '您确定执行此操作吗?';
	var successMsg = options.successMsg || '执行成功!';
	var successNotify = options.successNotify;
	var ajax = options.ajax == undefined ? true : options.ajax;
	
	var task;
	if(ajax) {
		task = function(){
			 $.ajax({
				 url : url,
				 dataType: 'json',
				 type: 'post',
				 success: function(dd) {
					 if(dd.success) {
						 if(successNotify) app.alert(successMsg);
						 if(callback) {callback()};
					 } 
				 },
				 error: function() {
					 console.log('服务器错误!');
				 }
			 });
		};
	} else {
		task = function() {
			window.location.href = url;
		};
	}
	
	if(confirm) {
		bootbox.confirm(confirmMsg, function(result){
			if(result) task();
		}); 
	} else {
		task();
	}
};

if(Messenger) {
	Messenger.options = {
		extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right',
		maxMessages: 9,
		parentLocations: ['body'],
		theme: 'ice'
	}
}
app.message = function(type, msg) {
	Messenger().post({
	  message: msg,
	  type: type,
	  showCloseButton: true
	});
};

app.info = function(msg) {
	app.message('info', msg);
};
app.error = function(msg) {
	app.message('danger', msg);
};
app.success = function(msg) {
	app.message('success', msg);
};

app.alert = function(msg, callback){
	bootbox.alert(msg, callback);
};

app.confirm = function(msg, callback, dismissCallback){
	bootbox.confirm(msg, function(result){
		if(result) {
			callback && callback();
		} else {
			dismissCallback && dismissCallback();
		}
	});
};

app.prompt = function(msg, callback){
	bootbox.prompt(msg, function(result){
		if(result) {
			callback(result);
		}
	});
};

app.popupDialog = function (options) {
	var url = options.url;
	var id = options.id;
	var title = options.title || '标题';
	var width = options.width || '560px';
	var height = options.height || '400px';
	var iframe = options.iframe ? true : false;
	var callback = options.callback || function(){};
	var disHeader=options.disHeader ? true : false;
	
	var buttons = options.buttons || {
		"关闭": {
	      label: "关闭",
	      className: "btn-primary",
	      callback: function() {}
		}
	};
	
	var dlg = bootbox.dialog({
		message: '加载中...',
		title: title,
		show: false,
		buttons: buttons
	});
	dlg.attr('id', id);
	
	var modalDlg = dlg.find('.modal-dialog');
	modalDlg.css('width', width);
	
	dlg.find('.modal-body').css('padding', '10px');
	if(disHeader){
		dlg.find('.modal-header').parent().css('top','30px');		
		dlg.find('.modal-header').find('button').css('display','none');
		dlg.find('.modal-footer').find('button').css('display','none');
	}
	dlg.on("hide.bs.modal", function() {
		
		var tcount = $("body").attr('extoverflowcount') || 0;
		tcount--;
		$("body").attr('extoverflowcount', tcount);
		if(tcount == 0) {
			$("body").css('overflow', 'auto');
		}
	});
	
	dlg.on("shown.bs.modal", function() {
		$("body").css('overflow', 'hidden');
		
		var tcount = $("body").attr('extoverflowcount') || 0;
		$("body").attr('extoverflowcount', ++tcount);
	});
	
	if(iframe) {
		dlg.on("shown.bs.modal", function() {
			callback();
		});
		
		var ifm = $("<iframe>");
		ifm.attr('src', url);
		ifm.css('margin', '0px');
		ifm.css('padding', '0px');
		ifm.css('border', 'none');
		ifm.css('width', '100%');
		ifm.css('height', 'auto');
		
		var con = dlg.find('.modal-body');
		con.empty();
		con.append(ifm);
		
		ifm.on("load", function(){
			var contentHeight = dlg.find('iframe')[0].contentWindow.$("body div:first").height();
			ifm.height(contentHeight + 20);
		});
	} else {
		dlg.on("shown.bs.modal", function() {
			$.ajax({
				url : url,
				dataType: 'html',
				type: 'post',
				success: function(dd) {
					dlg.find('.modal-body').html(dd);
					callback();
				},
				error: function() {
					console.log('服务器错误!');
				}
			});
		});
	}
	dlg.modal('show');
};

app.myPaginator = function (options) {
	var pageSize = options.pageSize || 10;
	var pageNo = options.pageNo || 1;
	var totalPages = options.totalPages || 0;
	var numberOfPages = options.numberOfPages || 5;
	var alignment = options.alignment || "center";
	var pageUrl = options.pageUrl;
	var element = options.element;
	
	var formId = options.formId;
	var containerId = options.containerId;
	
	var doUpdate = function(){
		var param = $("#" + formId).serialize();
		$.ajax({
			 url : pageUrl + "?pageNo=" + pageNo + "&pageSize=" + pageSize,
			 data: param,
			 dataType: 'html',
			 type: 'post',
			 success: function(html) {
				 $("#" + containerId).empty();
				 $("#" + containerId).append(html);
				 totalPages=$("#" + containerId).find('input').val();
				 var options = {
							bootstrapMajorVersion: 3,
					        currentPage: pageNo,
					        totalPages: totalPages,
					        size: 'normal',
					        alignment: alignment,
							numberOfPages: numberOfPages,
							tooltipTitles: function (type, page, current) {
					            switch (type) {
					                case "first":
					                    return "首页";
					                case "prev":
					                    return "上一页";
					                case "next":
					                    return "下一页";
					                case "last":
					                    return "最后页";
					                case "page":
					                    return "当前是第 " + page + " 页 ";
					            }
					        },
							pageUrl: function(type, page, current){
								return null;
					        },
					        onPageChanged: function(event, oldPage, newPage) {
					        	pageNo = newPage;
					        	doUpdate();
					        },
					        shouldShowPage:function(type, page, current){
					        	if(totalPages == 1) return false; // 不中一页时不显示分页组件
					            switch(type)
					            {
					                case "first":
					                	return current > 1;
					                case "prev":
					                	return current > 1;
					                case "next":
					                	return current < totalPages;
					                case "last":
					                	return current < totalPages;
					                default:
					                    return true;
					            }
					        }
					    };
				    $('#' + element).bootstrapPaginator(options);
			 },
			 error: function() {
				 console.log('服务器分页错误!');
			 }
		 });
	};
	
	var options = {
		bootstrapMajorVersion: 3,
        currentPage: pageNo,
        totalPages: totalPages,
        size: 'normal',
        alignment: alignment,
		numberOfPages: numberOfPages,
		tooltipTitles: function (type, page, current) {
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上一页";
                case "next":
                    return "下一页";
                case "last":
                    return "最后页";
                case "page":
                    return "当前是第 " + page + " 页 ";
            }
        },
		pageUrl: function(type, page, current){
			return null;
        },
        onPageChanged: function(event, oldPage, newPage) {
        	pageNo = newPage;
        	doUpdate();
        },
        shouldShowPage:function(type, page, current){
        	if(totalPages == 1) return false; // 不中一页时不显示分页组件
            switch(type)
            {
                case "first":
                	return current > 1;
                case "prev":
                	return current > 1;
                case "next":
                	return current < totalPages;
                case "last":
                	return current < totalPages;
                default:
                    return true;
            }
        }
    };
	if(formId) {
		$("#" + formId).find("button[type=submit]").click(doUpdate);
	}
	
    $('#' + element).bootstrapPaginator(options);
    return doUpdate;
};

app.checkboxToggle = function (obj, name) {
	var self = $(obj);
	if(self.attr('checked')) {
		$("table input:checkbox").attr('checked', true);
	} else {
		$("table input:checkbox").attr('checked', false);
	}
};


/**
 * 
 * @param options
 * options is a JSON object like this
 * { selector : '#aaa', just to select a element
 *   pickTime : true,  if need to pick time ignore it, true by default
 *   pickDate : true, if need to pick date ignore it, true by default
 *   changeEvent: function(ev){}, the event triggered when the date changed
 * }
 */
app.datetimePicker = function  (options) {
	var selector = options.selector;
	if(!selector) {
		alert('datetimePicker parameter is null, lack selector');
		return;
	}
	var startDate = options.startDate || null;
	var endDate = options.endDate || null;
	var startView = options.startView == undefined ? 2 : options.startView;
	var minView = options.minView == undefined ? 1 : options.minView; // 0 :精确到分， 1：精确到时， 2：精确到日， 3：精确到月，4：精确到年
	var maxView = options.maxView == undefined ? 4 : options.maxView;
	var todayBtn = options.todayBtn == false ? false : true;
	var forceParse = options.forceParse == false ? false : true;
	var minuteStep = options.minuteStep == undefined ? 5 : options.minuteStep;
	var weekStart = options.weekStart == undefined ? 1 : options.weekStart;
	var showMeridian = options.showMeridian == true ? true : false;
	var pickerPosition = options.pickerPosition || 'bottom-left';
	
	var changeEvent = options.changeEvent || function(ev) {};
	
	$(selector).datetimepicker({
		startDate: startDate,
		endDate: endDate,
		startView: startView,
		minView: minView,
		maxView: maxView,
		weekStart: weekStart,
		todayBtn:  todayBtn,
		forceParse: forceParse,
		showMeridian: showMeridian,
		pickerPosition: pickerPosition,
		language:  'zh-CN',
		autoclose: 1
	}).on('changeDate', changeEvent);
};

app.duallistbox = function(options) {
	$(options.selector).bootstrapDualListbox({moveonselect: false});
};

app.selectpicker = function(selector, options) {
	var options = options || {};
	options.countSelectedText = "{1}条中的 {0}条被选中";
	options.selectedText = "cat";
	$(selector).selectpicker(options);
};

app.fileupload = function(options){
	var selector = options.selector;
	if(!selector) {
		console.log('fileupload selector is null');
		return;
	}
	options.uploadTemplateId = options.uploadTemplateId || null;
	options.downloadTemplateId = options.downloadTemplateId || null;
	
	if(!options.defaultUploadTpl) {
		options.uploadTemplate = function (o) { 
			return $(new EJS({url: base + '/static/ejs/file/upload.ejs?rn=102'}).render(o));;
		};
	}
	if(!options.defaultDownloadTpl) {
		options.downloadTemplate = function (o) {
			return $(new EJS({url: base + '/static/ejs/file/download.ejs?rn=114'}).render(o));
		};
	}
	
	options.singleFileUploads = true;
	options.multipart = true;
	options.previewMaxWidth = options.previewMaxWidth || 120;
	options.previewMaxHeight = options.previewMaxHeight || 120;
	options.sequentialUploads = options.sequentialUploads == false ? false : true;
	options.singleFileUploads = options.singleFileUploads == false ? false : true;
	
	var doneEvent = options.doneEvent || function(){};
	var addEvent = options.addEvent || function(){};
	var submitEvent = options.submitEvent || function(){};
	var sendEvent = options.sendEvent || function(){};
	var failEvent = options.failEvent || function(){};
	var startEvent = options.startEvent || function(){};
	var stopEvent = options.stopEvent || function(){};
	var progressEvent = options.progressEvent || function(){};
	var progressallEvent = options.progressallEvent || function(){};
	
	var fileUpload = $(selector).fileupload(options);
	fileUpload.bind('fileuploaddone', doneEvent);
	fileUpload.bind('fileuploadadd', addEvent);
	fileUpload.bind('fileuploadsubmit', submitEvent);
	fileUpload.bind('fileuploadsend', sendEvent);
	fileUpload.bind('fileuploadfail', failEvent);
	fileUpload.bind('fileuploadprogress', progressEvent);
	fileUpload.bind('fileuploadprogressall', progressallEvent);
	fileUpload.bind('fileuploadstart', startEvent);
	fileUpload.bind('fileuploadstop', stopEvent);
	
	return fileUpload;
};

app.isEnterEvent = function (e) {
	return e.keyCode == 13;
};

app.enterEvent = function (e, func) {
	if(isEnterEvent(e)) {
		func();
	}
	return false;
};


app.changeCaptchaCode = function(id){
	var self = $("#" + id);
	var url = self.attr('data-ex-src') + '?rn=' + Math.random();
	self.attr('src', url);
};

app.showErrors = function(containerSelector, msgs) {
	var container = $(containerSelector);
	var messages = [];
	if(Object.prototype.toString.call(msgs) !== '[object Array]') {
		messages.push(msgs);
	}
	
	var errorElement = $('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span></span></div>');
	for(var i = 0 ; i < messages.length ;i++) {
		errorElement.find('span').text(messages[i] + ';');
	}
	container.empty();
	container.append(errorElement);
};

app.imgUpload = function(options) {
	var width = options.width || 200;
	var height = options.height || 200;
	var callback = options.callback || function(){};
	
	var buttons = {
    	a: {
    	      label: "取消",
    	      className: "btn-default",
    	      callback: function() { }
    	},
    	b: {
    	      label: "确定",
    	      className: "btn-primary",
    	      callback: function() {
    	    	  var top = $("#img_cut_upload_dlg").find(".cutOper");
    	    	  var fid = top.attr('imgId');
    	    	  var cut = top.attr('cut');
    	    	  if(!fid) {
    	    		  app.alert('请上传图片');
    	    		  return false;
    	    	  }
    	    	  if(cut != 'true') {
    	    		  app.alert('请剪切图片');
    	    		  return false;
    	    	  }
    	    	  callback(fid);
    	    	  return true;
    		  }
    	}
	};
		
	var options = {
		url: base + '/common/fileItem/toImgUpload?width=' + width + '&height=' + height,
		iframe: false,
		id: 'img_cut_upload_dlg',
		title: '图片上传',
		buttons: buttons,
		height: '580px',
		width: '900px'
	};
	app.popupDialog(options);
};

app.validateEngine = function(selector, options){
	options = options || {};
	options.promptPosition = options.promptPosition || 'bottomRight'; // "topLeft", "topRight", "bottomLeft", "centerRight", "bottomRight"
	options.scroll = options.scroll == undefined ? true : options.scroll;
	options.autoPositionUpdate = options.autoPositionUpdate == undefined ? true : options.autoPositionUpdate;
	options.autoHidePrompt = options.autoHidePrompt == undefined ? true : options.autoHidePrompt;
	options.autoHideDelay = options.autoHideDelay || 3000;
	options.showOneMessage = options.showOneMessage == undefined ? false : options.showOneMessage;
	options.showArrowOnRadioAndCheckbox = options.showArrowOnRadioAndCheckbox == undefined ? true : options.showArrowOnRadioAndCheckbox;
	options.onFieldSuccess = options.onFieldSuccess || function(field){
		var con = $(field).closest('.form-group');
		con.removeClass('has-error');
		con.addClass('has-success');
	};
	options.onFieldFailure = options.onFieldFailure || function(field){
		var con = $(field).closest('.form-group');
		con.removeClass('has-success');
		con.addClass('has-error');
	};
	
	
	return $(selector).validationEngine('attach', options);
};

app.data.groups = function() {
	if(!app.cache.groups) {
		$.ajax({
			url: base + '/open/allGroups',
			dataType: 'json',
			async: false,
			success: function(data) {
				app.cache.groups = data;
				app.dict.groups = {};
				for(var i = 0 ; i < data.length ; i++) {
					app.dict.groups[data[i].value] = data[i].text;
				}
			}
		});
	}
	return app.cache.groups;
};

app.data.emails = function() {
	if(!app.cache.emails) {
		$.ajax({
			url: base + '/open/allEmails',
			dataType: 'json',
			async: false,
			success: function(data) {
				app.cache.emails = data;
				app.dict.emails = {};
				for(var i = 0 ; i < data.length ; i++) {
					app.dict.emails[data[i].value] = data[i].text;
				}
			}
		});
	}
	return app.cache.emails;
};

app.xeditor = function(selector, options) {
	options.emptytext = options.emptytext || '无';
	options.ajaxOptions = {
		dataType: 'json'
	};
	
	$(selector).editable(options);
};

// 通过 hash 恢复 tab 状态
$(function(){
	$(document).on('shown.bs.tab', function(event) {
		window.location.hash = $(event.target).attr('href');
	});
	
});
